package com.chentf.cglib;

import com.chentf.entity.User;
import org.aspectj.weaver.ast.Test;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author chentengfei
 * @desc ...
 * @date 2021-01-24 16:58:33
 */
public class TestCglib {
    public static void main(String[] args) {
        //1.创建原始对象
        UserService userService = new UserService();
        /*
          2.通过cglib方式创建动态代理对象
            jdk创建动态代理方式
                proxy.newProxyInstance(classloader,interface,invocationhandler);
            cglib创建动态代理方式,原理一样
                Enhancer.setClassLoader();
                Enhancer.setSuperClass();
                Enhancer.setCallBack(); --> MethodInterceptor(cglib)
                Enhancer.create(); 创建代理
         */
        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(TestCglib.class.getClassLoader());
        enhancer.setSuperclass(userService.getClass());
        MethodInterceptor interceptor = new MethodInterceptor() {
            //等同于jdk动态代理的InvocationHandler --> invoke
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("----cglib log----");
                Object ret = method.invoke(userService, objects);
                return ret;
            }
        };
        enhancer.setCallback(interceptor);
        //获取的 是动态代理类而不是UserService
        UserService userServiceProxy = (UserService) enhancer.create();
        userServiceProxy.login("chentf", "123456");
        userServiceProxy.register(new User());
    }
}
